const character_comment = require('../dataBase/character_comment');

const createComment = async (req, res) => {
    try {
        const { characterId, content } = req.body;
        
        if (!characterId || !content) {
            return res.status(400).json({ error: 'Missing required fields' });
        }

        const userId = req.auth.user_id;
        const comment = await character_comment.create({ characterId, userId, content });
        res.status(201).json(comment);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
};

const getComment = async (req, res) => {
    try {
        const comment = await character_comment.findById(req.params.id);
        comment ? res.json(comment) : res.status(404).json({ error: 'Comment not found' });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
};

// 分页获取帖子评论
const getCharacterComments = async (req, res) => {
    try {
        const page = Number(req.query.page) || 1;
        const limit = Number(req.query.limit) || 10;
        const characterId = req.params.id;
        const [comments, total] = await Promise.all([
            character_comment.findByCharacterId(characterId, page, limit),
            character_comment.countByCharacterId(characterId)
        ]);

        res.json({
            data: comments,
            pagination: {
                page: Number(page),
                limit: Number(limit),
                total,
                totalPages: Math.ceil(total / limit)
            }
        });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
};

// 更新评论内容
const updateComment = async (req, res) => {
    try {
        const comment = await character_comment.updateContent(
            req.params.id,
            req.body.content
        );
        res.json(comment);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
};

// 删除评论
const deleteComment = async (req, res) => {
    try {
        await character_comment.delete(req.params.id);
        res.status(204).end();
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
};

module.exports = {
    createComment,
    getComment,
    getCharacterComments,
    updateComment,
    deleteComment
};